/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component} from 'react';
import {Form, Input, Radio, Select, Checkbox, TreeSelect, Drawer, Button, Modal,message} from 'antd';
import {connect} from 'dva';
import request from '@/utils/request';
import {renderTreeNodes,afterCloseModal} from '@/utils/utils';
import BuildModalTitle from '@/components/BuildModalTitle';
import type2 from './../../images/type2.jpg';
import type3 from './../../images/type3.jpg';
import AddOrEditNode from './addOrEditNode'
import Detail from "@/pages/Meters/Detail";
const CheckboxGroup = Checkbox.Group;
const FormItem = Form.Item;
const TreeNode = TreeSelect.TreeNode;
const Option = Select.Option;

class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      villages: [],
      editRecord: {},
      nodeDataArray: [],
      linkDataArray: [],
      modify: false,
      exitJson:{},
      showType:this.props.showType
    };
  }

  componentDidMount() {
    const that = this;
    let nodeDataArray = []
    let linkDataArray = []
    console.log('this.props.editRecord.graph_data',this.props.editRecord.graph_data)
    if (this.props.editRecord.graph) {
      nodeDataArray = this.props.editRecord.graph_data.vertexs
      linkDataArray = this.props.editRecord.graph_data.edges;
      for(let i=0;i<nodeDataArray.length;i++){
        nodeDataArray[i].explain1=`流入水量 : ${nodeDataArray[i].inflow_value.toFixed(2)} 流出水量 : ${nodeDataArray[i].outflow_value.toFixed(2)}`
        nodeDataArray[i].explain2=`损耗值 : ${nodeDataArray[i].attrition_value.toFixed(2)} 损耗率 : ${nodeDataArray[i].attrition_rate}`
        // let showExplain2=nodeDataArray[i].children.length>0
        let showExplain2=true
        let showButton=nodeDataArray[i].type===1
        let color='#44CCFF';
        if(nodeDataArray[i].attrition_rate==='-'){
          color='#b0b0b0';
        }else if(parseFloat(nodeDataArray[i].attrition_rate)<10){
          color='#009688';
        }else if(parseFloat(nodeDataArray[i].attrition_rate)<20){
          color='#d7bb00';
        }else if(parseFloat(nodeDataArray[i].attrition_rate)<30){
          color='#ff7400';
        }else{
          color='#d20000';
        }
        nodeDataArray[i].color=color
        nodeDataArray[i].showExplain2=showExplain2
        nodeDataArray[i].showButton=showButton
      }
      for(let j=0;j<linkDataArray.length;j++){
        if(linkDataArray[j].type===1){
          linkDataArray[j].visible=true
        }else{
          linkDataArray[j].visible=true
        }
      }
      this.setState({
        linkDataArray, nodeDataArray
      }, function () {
        that.renderGraph();
      })

    } else {
      that.renderGraph();
    }


  }

  renderGraph = () => {
    const {
      nodeDataArray, linkDataArray
    } = this.state;
    const showType=this.props.showType
    let showLinkDataArray=[]
    if(showType==='1'){
      for(let i=0;i<linkDataArray.length;i++){
        if(linkDataArray[i].type===1){
          showLinkDataArray.push(linkDataArray[i])
        }
      }
    }
    if(showType==='2'){
      for(let i=0;i<linkDataArray.length;i++){
        if(linkDataArray[i].type===2){
          showLinkDataArray.push(linkDataArray[i])
        }
      }
    }
    if(showType==='0'){
      showLinkDataArray=linkDataArray
    }
    const that = this;
    const $ = window.$;
    const go = window.go
    const myDiagram = this.myDiagram =
      $(go.Diagram, this.props.type==='modal'?'myDiagramDiv_modal':'myDiagramDiv',
        {
          'toolManager.mouseWheelBehavior': go.ToolManager.WheelZoom,
          'undoManager.isEnabled': true, // enable Ctrl-Z to undo and Ctrl-Y to redo
          'LinkDrawn': showLinkLabel,  //画线
          'toolManager.hoverDelay': 300,
          click:clickDiagram
        });

    myDiagram.addDiagramListener("Modified", function (e) {
      // that.setState({
      //     hadEdit:true
      // })
      console.log('modify')
      that.setState({
        modify: true,
      })
    });
    function clickDiagram(){
      console.log('clickDiagram')
      refleshLink()
    }
    // 监听点击
    myDiagram.addDiagramListener("ObjectSingleClicked", (e) => {
      console.log('click ObjectSingleClicked')
      //这是清除高亮的
      // e.diagram.commit((d) => {
      //      d.clearHighlighteds();
      // }, "no highlighteds");
      refleshLink()

    });
    function refleshLink(){
      for (var nit = that.myDiagram.nodes; nit.next(); ) {
        var node = nit.value;
        // console.log(node.data)
        node.findLinksOutOf().each(function(l) {
          if(l.data.type===1){
            l.visible = false;
          }else{
            l.visible = true;
          }

        });
        node.findLinksInto().each(function(l) {
          if(l.data.type===1){
            l.visible = false;
          }else{
            l.visible = true;
          }
        });
      }
    }
    function showLinkLabel(e) {
      console.log('e', e);
      var label = e.subject.findObject('LABEL');
      console.log('label', label);
      if (label !== null) label.visible = false;//如果figure=Diamond则线的文字可以编辑
    }

    myDiagram.grid = $(go.Panel, 'Grid',
      $(go.Shape, 'LineH', {stroke: 'gray', strokeWidth: 0.5}),
      $(go.Shape, 'LineH', {stroke: 'darkslategray', strokeWidth: 1.5, interval: 10}),
      $(go.Shape, 'LineV', {stroke: 'gray', strokeWidth: 0.5}),
      $(go.Shape, 'LineV', {stroke: 'darkslategray', strokeWidth: 1.5, interval: 10}),
    );
    myDiagram.toolManager.draggingTool.isGridSnapEnabled = true;
    myDiagram.undoManager.isEnabled = true;
    // define a simple Node template
    myDiagram.nodeTemplate =
      $(go.Node, 'Auto',
        {
          click: function(e, node) {
            // highlight all Links and Nodes coming out of a given Node
            console.log('node click')
            // let diagram = node.diagram;
            // diagram.startTransaction("highlight");
            // remove any previous highlighting
            // diagram.clearHighlighteds();
            // for each Link coming out of the Node, set Link.isHighlighted
            node.findLinksOutOf().each(function(l) {
              l.visible = true;
            });
            node.findLinksInto().each(function(l) {
              l.visible = true;
            });
            // for each Node destination for the Node, set Node.isHighlighted
            // node.findNodesOutOf().each(function(n) { n.isHighlighted = true; });
            // diagram.commitTransaction("highlight");
          }
        },
        new go.Binding('location', 'loc', go.Point.parse).makeTwoWay(go.Point.stringify),
        $(go.Shape, 'RoundedRectangle', new go.Binding('fill', 'color'),
          { fill: '#CC5245', portId: '', strokeWidth: 1, stroke: 'black', toEndSegmentLength: 150 }),
        $(go.Panel, 'Horizontal',
          $(go.Picture,
            // Pictures should normally have an explicit width and height.
            // This picture has a red background, only visible when there is no source set
            // or when the image is partially transparent.
            { width: 60, height: 60, background: 'red' },
            // Picture.source is data bound to the "source" attribute of the model data
            new go.Binding('source')),
          $(go.Panel, 'Vertical',
            $(go.TextBlock,
              'Default Text',  // the initial value for TextBlock.text
              // some room around the text, a larger font, and a white stroke:
              {
                margin: 2, height: 18, stroke: '#ffffff', font: 'bold 16px sans-serif',
                verticalAlignment: go.Spot.Center, editable: false,
              },
              // TextBlock.text is data bound to the "name" attribute of the model data
              new go.Binding('text', 'name')),
            $(go.TextBlock,
              '',  // the initial value for TextBlock.text
              // some room around the text, a larger font, and a white stroke:
              {
                margin: 4, height: 16, stroke: 'white', font: '15px sans-serif',
                verticalAlignment: go.Spot.Center, editable: false,
              },
              // TextBlock.text is data bound to the "name" attribute of the model data
              new go.Binding('text', 'explain1')),
            $(go.TextBlock,
              '',  // the initial value for TextBlock.text
              // some room around the text, a larger font, and a white stroke:
              {
                margin: 4, height: 18, stroke: 'white', font: '15px sans-serif',
                verticalAlignment: go.Spot.Center, editable: false,
              },
              // TextBlock.text is data bound to the "name" attribute of the model data
              new go.Binding('visible', 'showExplain2'),
              new go.Binding('text', 'explain2')),
            $('Button',
              {
                margin: 2,
                click: incrementCounter,
              },
              new go.Binding('visible', 'showButton'),
              $(go.TextBlock, '查看水表')),
          ),
        ),
        makePort('T', go.Spot.Top, true, true),//创建点，顶点不可输出，可以输入
        makePort('L', go.Spot.Left, true, true),
        makePort('R', go.Spot.Right, true, true),
        makePort('B', go.Spot.Bottom, true, true),
      );

    function incrementCounter(e, obj) {
      console.log('e', e)
      console.log('obj', obj.diagram.div.id)
      var node = obj.part;
      var data = node.data;
      console.log('data', data);
      if (data) {
        if (obj.diagram.div.id === 'myPaletteDiv') {
          return
        }
        node.diagram.model.commit(function (m) {
          that.setState({
            editRecord: data,
            infoModal: true,
          });
          // m.set(data, 'name', '123');
        }, 'clicked');
      }
    }

    function showPorts(node, show) {
      var diagram = node.diagram;
      if (!diagram || diagram.isReadOnly || !diagram.allowLink) return;
      node.ports.each(function (port) {
        port.stroke = (show ? 'black' : null);
      });
    }

    function makePort(name, spot, output, input) {
      // the port is basically just a small circle that has a white stroke when it is made visible
      return $(go.Shape, 'Circle',
        {
          fill: 'transparent',
          stroke: null,  // this is changed to "white" in the showPorts function
          desiredSize: new go.Size(8, 8),
          alignment: spot, alignmentFocus: spot,  // align the port on the main Shape
          portId: name,  //点属性的描述 declare this object to be a "port"
          fromSpot: spot, toSpot: spot,  // declare where links may connect at this port
          fromLinkable: output, toLinkable: input,  //输入和输出 declare whether the user may draw links to/from here
          cursor: 'pointer',  // show a different cursor to indicate potential link point
        });
    }

    //流动的线
    myDiagram.linkTemplate =
      $(go.Link,
        new go.Binding('points').makeTwoWay(),
        new go.Binding("visible", "visible"),
        // mark each Shape to get the link geometry with isPanelMain: true
        $(go.Shape, { isPanelMain: true, stroke: 'black', strokeWidth: 7 }),
        $(go.Shape,
          new go.Binding('stroke', 'color',function (params){
            if(params){
              return params
            }else{
              return 'blue'
            }
          }),
          { isPanelMain: true,  strokeWidth: 5 }),
        $(go.Shape, { isPanelMain: true, stroke: 'white', strokeWidth: 3, name: 'PIPE', strokeDashArray: [10, 10] }),
        // $(go.Shape, { toArrow: "Triangle", scale: 2, fill: "blue" })
        $(go.Shape,
          new go.Binding('fill', 'color',function (params){
            if(params){
              return params
            }else{
              return 'blue'
            }
          }),
          {
            stroke: null,
            toArrow: "Standard",
            scale:3
          })
      );


    var model = $(go.GraphLinksModel);
    model.nodeDataArray = nodeDataArray;
    model.linkDataArray = showLinkDataArray;
    myDiagram.model = model;
    myDiagram.commandHandler.zoomToFit();
    // Animate the flow in the pipes
    var animation = new go.Animation();
    animation.easing = go.Animation.EaseLinear;
    myDiagram.links.each(function (link) {
      animation.add(link.findObject('PIPE'), 'strokeDashOffset', 20, 0);
    });
    // Run indefinitely
    animation.runCount = Infinity;
    animation.start();


  };
  getJson = () => {
    const tojson = this.myDiagram.model.toJson();
    return JSON.parse(tojson);
  };
  saveGraph=()=>{
    const getJson = this.getJson();
    console.log('getJson', getJson);
    const that = this;
    for(let i=0;i<getJson.nodeDataArray.length;i++){
      if(typeof(getJson.nodeDataArray[i].key)!=='string'){
        console.log(getJson.nodeDataArray[i])
        message.error(`节点‘${getJson.nodeDataArray[i].name}’错误,请检查`)
        return false
      }
    }

    request(`/areas/${this.props.editRecord.id}/graph`, {
      method: 'PUT',
      data:{
        graph:{
          vertexs: getJson.nodeDataArray,
          edges: getJson.linkDataArray,
        }
      }
    }).then((response) => {
      if (response.status === 200) {
        message.success('修改水表关系成功');
        that.props.handleSearch()
        that.props.onClose()
      }
    });
    return
    this.props.dispatch({
      type: `meters_graph/edit`,
      payload: {
        id: data.id,
        name: data.name,
        vertexs: getJson.nodeDataArray,
        edges: getJson.linkDataArray,
      },
      callback() {
        message.success('修改水表关系成功');
        that.myDiagram.isModified = false;
        that.props.dispatch({
          type: `meters_graph/changeOneState`,
          payload: {
            modify:false,
          },
        })
      },
    });
  }
  handleEdit=()=>{
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues',formValues)
    if(this.state.graphModel){
      if(this.state.editRecord.type===2||this.state.editRecord.type===3){
        this.state.graphModel.set(this.state.editRecord, 'key', formValues.name)
        this.state.graphModel.set(this.state.editRecord, 'name', formValues.name)
        // this.state.graphModel.set(this.state.editRecord, 'analyze_consumption', formValues.analyze_consumption)
      }else if(this.state.editRecord.type===4){
        if(!formValues.workstation.key){
          message.error('请选择一个工作站点')
          return
        }
        this.state.graphModel.set(this.state.editRecord, 'key', formValues.workstation.key)
        this.state.graphModel.set(this.state.editRecord, 'name', formValues.workstation.label)
      }else if(this.state.editRecord.type===5){
        if(!formValues.dma.value){
          message.error('请选择一个DMA分区')
          return
        }
        this.state.graphModel.set(this.state.editRecord, 'key', formValues.dma.value)
        this.state.graphModel.set(this.state.editRecord, 'name', formValues.dma.label)
      }else{
        if(!formValues.meter){
          message.error('请选择一个水表')
          return
        }
        this.state.graphModel.set(this.state.editRecord, 'key', formValues.meter.key)
        this.state.graphModel.set(this.state.editRecord, 'name', formValues.meter.label)
        // this.state.graphModel.set(this.state.editRecord, 'analyze_consumption', formValues.analyze_consumption)
      }
      this.myDiagram.isModified = true;
      this.setState({
        editModal:false
      })
    }

  }
  render() {
    const that = this;
    const {
      graph
    } = this.props;

    return <div style={{
      height: '100%',
      width: '100%',
      overflow: 'hidden',
    }}>
      <div id={'grapDiv'} style={{
        display: 'flex',
        height: '80vh',

        background: '#000',
        postion: 'relative',
      }}>
        <div id={ this.props.type==='modal'?'myDiagramDiv_modal':'myDiagramDiv'} style={{flex: 1, backgroundColor: '#DAE4E4'}}>

        </div>
      </div>
 {/*      <div
        style={{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
        }}
      >
        <Button onClick={this.props.cancel} style={{marginRight: 8}}>
          取消
        </Button>
        <Button onClick={this.saveGraph} type="primary">
          确定
        </Button>
      </div> */}
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`更改节点`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        className="editModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({editModal: false, editRecord: {}});
        }}

      >
        <AddOrEditNode
          exitJson={this.state.exitJson}
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}/>
      </Modal>
      <Drawer
        title={`${this.state.editRecord.name} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={700}
        visible={this.state.infoModal}
      >
        <Detail id={this.state.editRecord.key}></Detail>
      </Drawer>
    </div>;
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);


